/*
 * Created on Wed Jun 06 2018 by Ronnie Ren (zhaosong.ren) from Accenture
 *
 * Copyright (c) 2018 DingXing information & technology limited company.
 */

import { Injectable } from "@angular/core";
// import { UserService } from "../models/transform.service";
import { SqliteService } from "../../../services/sqliteDB/sqlite.service";
// import { BillService } from "./bill.service";

import {JsonMappingUtil} from "../../json-mapping-util";
import {InspectionOperationsTickets} from '../../transform/inspection/inspection-operation-tickets';
import {InspectionOperationsTicketsDto} from '../../dto/inspection/inspection-operation-tickets.dto';
import { Observable } from "rxjs";
import { CurdService } from "../curd.service";
import { SyncUtilService } from "../../../services/offline/sync.util.service";
// import {InspectionRecordsDto} from "../../dto/inspection/inspection-records.dto";
import {SyncStatus} from "../../sync-status";
import {AttachmentService} from "../attachment.service";
import {ConditionFetch} from "../../../services/sqliteDB/condition-fetch";
// import {InspectionRecords} from "../../transform/inspection/inspection-records";
// import {InspectionRecordsDto} from "../../dto/inspection/inspection-records.dto";
// import {InspectionRecords} from "../../transform/inspection/inspection-records";



@Injectable()
export class InspectionOperationsTicketsService {

    constructor(
        private sqliteService: SqliteService,
        private curdService: CurdService,
        private attachmentService: AttachmentService,
        private syncUtilService: SyncUtilService
    ) {

    }

    fetchInspectionOperationTicketsBySyncStatus(syncStatuses: Array<SyncStatus>, count: number = 1): Observable<Array<InspectionOperationsTickets>> {
      return this.curdService.observableFetchObjectsByPage(
        InspectionOperationsTicketsDto,
        null,
        [{ syncStatus: syncStatuses }]
      )
        .flatMap((inspectionOperationsTicketsDtos: Array<InspectionOperationsTicketsDto>) => {
          if (!inspectionOperationsTicketsDtos || inspectionOperationsTicketsDtos.length < 1 ) {
            return Observable.of([]);
          } else {
            return Observable.combineLatest(
              inspectionOperationsTicketsDtos.map((inspectionOperationsTicketsDto) =>
                this.getInspectionOperationTicketsAndAttachmentsFromInspectionOperationTicketsDtos(inspectionOperationsTicketsDto))
            )
              .map((billsArray) => billsArray.reduce((result, bills) => result.concat(bills), []));
          }
        });
    }

    fetchInspectionOperationTicketsByCondition(condition: ConditionFetch, orderBy: Array<string> = []):
      Observable<Array<InspectionOperationsTicketsDto>> {
      return Observable.fromPromise(this.curdService.fetchByCondition(InspectionOperationsTicketsDto,
        condition, orderBy))
        .map((results) => {
          return Array.from(results["results"]);
        })
        .map((results) => {
          return results.map((row: any) => {
            let inspectionOperationsTicketsDto: any = new InspectionOperationsTicketsDto();
            JsonMappingUtil.MappingAllProp(row, inspectionOperationsTicketsDto);
            return inspectionOperationsTicketsDto;
          });
        });
    }

    getInspectionOperationTicketsAndAttachmentsFromInspectionOperationTicketsDtos(inspectionOperationsTicketsDto: InspectionOperationsTicketsDto):
      Observable<InspectionOperationsTickets> {
      let inspectionOperationsTicket = new InspectionOperationsTickets({});
      JsonMappingUtil.MappingAllProp(inspectionOperationsTicketsDto, inspectionOperationsTicket);
      return this.attachmentService.fetchAttachmentByIds(inspectionOperationsTicket.attachmentIds.split(","))
        .do((attachments) => {
          console.log(attachments, "attachments ------");
          inspectionOperationsTicket.pictureAttachments = attachments;
          console.log(inspectionOperationsTicket, "inspectionRecord ------");
        })
        .map(() => {
          console.log(inspectionOperationsTicket);
          return inspectionOperationsTicket;
        });
    }

    getOperationTickets(plannedId: string) {
        return this.curdService.observableFetchObjects(InspectionOperationsTicketsDto , {taskId: plannedId})
        .map((objs: Array<{}>) => {
            if (objs && objs.length > 0) {
                let dto = new InspectionOperationsTicketsDto();
                return JsonMappingUtil.MappingAllProp(objs[0], dto);
            }
            return null;
        })
        .map((dto) => {
            if (dto) {
                let model = new InspectionOperationsTickets({});
                return JsonMappingUtil.MappingAllProp(dto, model);
            }
            return null;

        });
    }

    addRecords(data) {
        return this.curdService.addRows([this.syncUtilService.toObjectDto(data, InspectionOperationsTicketsDto)]);
    }

    updateRecords(data) {
        return this.curdService.updateRow(
            this.syncUtilService.toObjectDto(data, InspectionOperationsTicketsDto),
            {taskId:  data.taskId});
    }


}
